package com.atguigu.srb.mq.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author lsyandwh
 * @create 2022-12-20 11:13
 */
@Component
public class MqConfirmConfig implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init(){
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
    }

    /**
     * 交换机接收消息确认
     * @param correlationData
     * @param ack
     * @param errorMessage
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String errorMessage) {

        if(ack){
            System.out.println("交换机成功接收消息");
        }else {
            System.out.println("交换机接收消息失败:" + errorMessage);
        }
    }

    /**
     * 队列接收消息失败回调函数
     * @param message
     * @param code
     * @param errorMessage
     * @param exchange
     * @param route
     */
    @Override
    public void returnedMessage(Message message, int code, String errorMessage, String exchange, String route) {

        System.out.println("message = " + new String(message.getBody()));

        System.out.println("errorMessage = " + errorMessage);
    }
}
